//
//  HomeTableViewController.swift
//  MyWeibo
//
//  Created by cat on 15/7/28.
//  Copyright © 2015年 cat. All rights reserved.
//

import UIKit

class HomeTableViewController: BaseTableViewController {

    var statuses: [Status]? {
        didSet {
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 如果用户没有登录,返回访客视图
        if !UserAccount.userLogon {
            visitorView?.stupInfo(true, imageName: "visitordiscover_feed_image_smallicon", messageName: "关注一些人，回这里看看有什么惊喜关注一些人，回这里看看有什么惊喜")
            
            return
        }
        
        prepareTableView()
        loadData()
    }
    
    private func prepareTableView() {
        // 注册cell
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: StatusCellIdentifier.NormalCell.rawValue)
        tableView.registerClass(StatusForwardCell.self, forCellReuseIdentifier: StatusCellIdentifier.ForwardCell.rawValue)

        // 预估行高
        tableView.estimatedRowHeight = 300
        // 取消分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        // 刷新控件
        refreshControl = XBXUIRefreshControl()
        
        // 添加监听方法
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
    }
    
    /// 上拉刷新的标记
    private var pullupRefreshFlag = false
    
    
    /// 加载数据
    private func loadData() {
        refreshControl?.beginRefreshing()
        
        var since_id = statuses?.first?.id ?? 0
        // 判断是否上拉刷新
        var max_id = 0
        
        if pullupRefreshFlag {
            
            since_id = 0
            // 记录数组最后一条
            max_id = statuses?.last?.id ?? 0
        }
        
        Status.loadStatus(since_id, max_id: max_id) { (dataList, error) -> () in
            // 关闭刷新控件
            self.refreshControl?.endRefreshing()
            
            if error != nil {
                print(error)
                return
            }
            
            let count = dataList?.count ?? 0
            
            if since_id > 0 {
            // 下拉刷新提示
                self.showPulldownTip(count)
            }
            // 无数据直接返回
            if count == 0 {
                return
            }
            
            if since_id > 0 {
                self.statuses = dataList! + self.statuses!
            } else if max_id > 0 {
                
                self.statuses! += dataList!
                
                self.pullupRefreshFlag = false
                
            } else {
                self.statuses = dataList
            }
        }
    }
    
    /// 下拉显示刷新的数据条数
    private func showPulldownTip(count: Int) {
        
        if tipLabel.layer.animationForKey("position") != nil {
            print("动画正在执行")
            
            return
        }
        
        tipLabel.text = (count == 0) ? "暂时没有新的微博" : "刷新到 \(count) 条微博"
        
        // 标签的初始位置
        let rect = tipLabel.frame
        
        UIView.animateWithDuration(2.0, animations: { () -> Void in
            // 自动反转动画
            UIView.setAnimationRepeatAutoreverses(true)
            // 移除 label的位置
            self.tipLabel.frame = CGRectOffset(rect, 0, 3 * rect.height)
            
            }) { (_) -> Void in
                
                self.tipLabel.frame = rect
        }

    }
    
    
    // MARK: - 数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let status = statuses![indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellIdentifier.cellId(status), forIndexPath: indexPath) as! StatusCell
        
        // 判断indexpath的数值
        if indexPath.row == statuses!.count - 1 {
            // 设置上拉刷新
            pullupRefreshFlag = true
            // 刷新数据
            loadData()
        }
        
        cell.status = statuses![indexPath.row]
        
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        let status = statuses![indexPath.row]
        
        if let h = status.rowHeight {
            
            return h
        }
        
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellIdentifier.cellId(status)) as? StatusCell
        
        status.rowHeight = cell!.rowHeight(status)
        
        return status.rowHeight!
    }
    // MARK: - 懒加载
    private lazy var tipLabel: UILabel = {
        let h: CGFloat = 44
        let label = UILabel(frame: CGRect(x: 0, y: -2 * h, width: self.view.bounds.width, height: h))
        label.backgroundColor = UIColor.orangeColor()
        label.textColor = UIColor.whiteColor()
        label.textAlignment = NSTextAlignment.Center
        
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        
        return label
    }()
    
    
}
